package pub.developers.forum.portal.controller.rest;

import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import pub.developers.forum.api.model.ResultModel;
import pub.developers.forum.api.request.file.FileUploadImgRequest;
import pub.developers.forum.api.request.user.UserRegisterRequest;
import pub.developers.forum.api.service.FileApiService;
import pub.developers.forum.common.constant.Constant;
import pub.developers.forum.common.enums.ErrorCodeEn;
import pub.developers.forum.common.support.CheckUtil;
import pub.developers.forum.common.support.StringUtil;
import pub.developers.forum.facade.support.ResultModelUtil;
import pub.developers.forum.portal.support.WebUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.List;
import java.util.Set;


@Slf4j
@RestController
@RequestMapping("/file-rest")
public class FileRestController {

    @Resource
    private FileApiService fileApiService;

    // .css;.js;.png;.jpeg;.jpg;.woff2;.html;.ico;.gif;.bmp;.svg;.woff;.map
    private static final Set<String> ALLOW_TYPES = Sets.newHashSet("png", "jpeg", "jpg", "ico", "gif", "bmp", "svg");


//    @PostMapping("/upload-wang-editor")
//    public JSONObject upload0(@RequestParam(value = "image") MultipartFile file, HttpServletRequest request) {
//        String fileName = StringUtil.generateUUID();
//        ResultModel<String> resultModel = uploadFile(file, fileName, request);
//
//        JSONArray urlArr = new JSONArray();
//
//        int errno = 0;
//        if (!resultModel.getSuccess()) {
//            errno = resultModel.getCode();
//        } else {
//            JSONObject url = new JSONObject();
//            url.put("url", resultModel.getData());
//            url.put("alt", fileName);
//            url.put("href", resultModel.getData());
//
//            urlArr.add(url);
//        }
//
//        JSONObject res = new JSONObject();
//        res.put("errno", errno);
//        res.put("data", urlArr);
//        return res;
//    }

    @PostMapping("/upload")
    public ResultModel<String> upload(@RequestParam(value = "image") List<MultipartFile> files, @RequestParam (value = "type" , required = false , defaultValue = "-1" ) int type ,  HttpServletRequest request) throws ParseException {
        String fileName = StringUtil.generateUUID();
        String result = uploadFile(files, type , fileName, request);
        ////System.out.println("审核结果"+result);
        if (result.isEmpty()) {
            return ResultModelUtil.fail(ErrorCodeEn.IMAGE_IS_NOPASS);
        }
        return ResultModelUtil.success(result);
    }

    //用户删除头像列表中的图片
    @PostMapping("/delete")
    public ResultModel deleteAvatarList(@RequestBody UserRegisterRequest avatar , HttpServletRequest request)
    {
        //验证用户登录状态 , 获取用户的登录信息
        request.setAttribute(Constant.REQUEST_HEADER_TOKEN_KEY , WebUtil.cookieGetSid(request));
        //先把oss上的照片删除
        if (!fileApiService.deleteImgOss(avatar.getAvatar()).getSuccess())
        {
            //如果删除失败
            return ResultModelUtil.fail(ErrorCodeEn.NO_EXIST_IMAGE);
        }
        //更新数据库中的数据
        return ResultModelUtil.success();
    }

    private String uploadFile(List<MultipartFile> files, int type , String fileName, HttpServletRequest request) throws ParseException {
        request.setAttribute(Constant.REQUEST_HEADER_TOKEN_KEY, WebUtil.cookieGetSid(request));
        StringBuilder sb = new StringBuilder();
        for (MultipartFile file : files)
        {
            String fileType = file.getContentType();
            boolean isAllowType = false;
            for (String allowType : ALLOW_TYPES) {
                if (fileType != null && fileType.contains(allowType)) {
                    isAllowType = true;
                    break;
                }
            }
            CheckUtil.isFalse(isAllowType, ErrorCodeEn.FILE_UPLOAD_NOT_SUPPORT_IMG_TYPE);

            FileUploadImgRequest uploadImgRequest = null;
            try {
                uploadImgRequest = FileUploadImgRequest.builder()
                        .base64(file.getBytes())
                        .fileName(fileName+file.getOriginalFilename())
                        .type(type) //类型 1 :官方上传图片不能压缩 , 0:用户上传图片 , 需要压缩使用
                        .build();
            } catch (Exception e) {
                CheckUtil.isTrue(true, ErrorCodeEn.FILE_UPLOAD_FAIL);
            }
            ResultModel<String> imageStr = fileApiService.uploadImgOss(uploadImgRequest);
            String temp = imageStr.getData();
            if (temp == null) {
                continue;
            }
            sb.append("https://").append(temp).append(" ");
        }
        return sb.toString();
    }

}
